<template>
    <div class="show-bg">
        <div class="toolbar">
            <el-button type="primary" @click="onAdd">+ 新增</el-button>
            <el-button type="danger" :disabled="!multipleSelection.length" @click="onBatchDelete">删除</el-button>
        </div>
        <div class="table-container">
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange" border>
                <el-table-column type="selection" width="50" />
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="goodsName" label="商品名称" width="110" />
                <el-table-column prop="production_Batch" label="生产批次" width="90" />
                <el-table-column prop="quality_Guarantee" label="保质期" width="70" />
                <el-table-column prop="production_License" label="生产许可证号" width="140" />
                <el-table-column prop="manufacturing_Enterprise" label="生产企业" width="220" />
                <el-table-column prop="information_Completeness" label="信息完整度" width="100">
                    <template #default="scope">
                        <el-tag
                            :type="scope.row.information_Completeness === '100' ? 'success' : (scope.row.information_Completeness === '80' ? 'warning' : 'danger')">
                            {{ scope.row.information_Completeness + '%' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createName" label="创建人" width="70" />
                <el-table-column prop="createTime" label="操作时间" width="160">
                    <template #default="scope">
                        {{ scope.row.createTime.substring(0, 19).replace("T", " ") }}
                    </template>
                </el-table-column>
                <el-table-column prop="updateName" label="修改人" width="70" />
                <el-table-column label="操作" width="210">
                    <template #default="scope">
                        <el-link type="primary" @click="onDetail(scope.row)">详情</el-link>
                        <el-link type="warning" @click="onEdit(scope.row)" style="margin-left:8px;">修改</el-link>
                        <el-link type="success" @click="openExportDialog(scope.row)"
                            style="margin-left:8px;">导出溯源码</el-link>
                        <el-link type="danger" @click="onDelete(scope.row.traceabilityId)"
                            style="margin-left:8px;">删除</el-link>
                    </template>
                </el-table-column>
            </el-table>
            <br />
            <el-pagination v-model:current-page="form.index" v-model:page-size="form.size" :page-sizes="[3, 5, 8, 10]"
                :background="true" layout="total, sizes, prev, pager, next, jumper" :total="form.count" next-text="下一页"
                prev-text="上一页" />
        </div>
        <!-- 新增弹窗 -->
        <el-dialog v-model="addDialogVisible" :title="isEdit ? '修改信息' : '基本信息'" width="500px"
            :close-on-click-modal="false" @close="onDialogClose">
            <el-form :model="addForm" label-width="130px" :rules="addRules" ref="addFormRef">
                <el-form-item label="商品名称：" prop="goodsId" required>
                    <el-select v-model="addForm.goodsId" placeholder="请选择商品名称" style="width: 100%">
                        <el-option v-for="item in data" :label="item.goodsName" :value="item.goodsId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="生产批次：" prop="production_Batch" required>
                    <el-input v-model="addForm.production_Batch" placeholder="请输入生产批次" />
                </el-form-item>
                <el-form-item label="保质期（天）：" prop="quality_Guarantee" required>
                    <el-input v-model="addForm.quality_Guarantee" placeholder="请输入保质期" />
                </el-form-item>
                <el-form-item label="生产许可证号：" prop="production_License" required>
                    <el-input v-model="addForm.production_License" placeholder="请输入生产许可证号" />
                </el-form-item>
                <el-form-item label="生产企业：" prop="manufacturing_Enterprise" required>
                    <el-input v-model="addForm.manufacturing_Enterprise" placeholder="请输入生产企业" />
                </el-form-item>
                <!-- <el-form-item label="信息完整度：" prop="information_Completeness" required>
                    <el-input v-model="addForm.information_Completeness" placeholder="请输入信息完整度" />
                </el-form-item> -->
                <el-form-item label="封面图：" prop="cover_Image">
                    <el-upload class="avatar-uploader" :show-file-list="false" :http-request="handleCoverChange">
                        <template #default>
                            <img v-if="addForm.cover_Image" :src="addForm.cover_Image" class="avatar" />
                            <div v-else class="avatar-uploader-icon">
                                <i class="el-icon-plus"></i>
                            </div>
                        </template>
                    </el-upload>
                    <el-button type="danger" size="small" @click="deleteCoverImage" v-if="addForm.cover_Image"
                        style="margin-top: 10px;">删除封面图</el-button>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="addDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="onAddSave">保存</el-button>
            </template>
        </el-dialog>
        <!-- 导出溯源码弹窗 -->
        <el-dialog v-model="exportDialogVisible" title="导出设置" width="440px" :close-on-click-modal="false">
            <el-form label-width="100px">
                <el-form-item label="导出数量：">
                    <el-input-number v-model="exportCount" :min="1" :max="9999" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="exportDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="onExport">导出</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';
import { Read, Write } from '@/components/Http/axiosHepler';
import { useRouter } from 'vue-router';
import { useCounterStore } from "@/stores/counter";

const router = useRouter();
const store = useCounterStore();
const addDialogVisible = ref(false);
const exportDialogVisible = ref(false);
const exportCount = ref(1);
const multipleSelection = ref<any[]>([]);
const addFormRef = ref();
let exportRow = ref<any>(null);
const isEdit = ref(false);
const editId = ref(null);

const tableData = ref([
    // { index: 1, productName: '兔腿（小）', batch: '20210718', shelfLife: 12, license: 'SC213205427680', company: '成都市爱吃兔食品加工有限公司', infoPercent: '100%' },
    // { index: 2, productName: '兔腿（大）', batch: '20210718', shelfLife: 12, license: 'SC213205427680', company: '成都市爱吃兔食品加工有限公司', infoPercent: '60%' },
    // { index: 3, productName: '兔肉丝', batch: '20210718', shelfLife: 12, license: 'SC213205427680', company: '成都市爱吃兔食品加工有限公司', infoPercent: '80%' },
    // { index: 4, productName: '兔肉丁', batch: '20210718', shelfLife: 12, license: 'SC213205427680', company: '成都市爱吃兔食品加工有限公司', infoPercent: '100%' },
    // { index: 5, productName: '冷吃兔', batch: '20210718', shelfLife: 12, license: 'SC213205427680', company: '成都市爱吃兔食品加工有限公司', infoPercent: '100%' },
]);

const form = reactive({
    index: 1,
    size: 5,
    count: 0,
    pagecount: 0,
})

const GetTraceability = () => {
    Read.get("/Management/TraceabilityShow", {
        params: {
            index: form.index,
            size: form.size,
        }
    }).then(res => {
        tableData.value = res.data.data.items;
        form.count = res.data.data.count;
        form.pagecount = res.data.data.pagecount;
    })
}

const addForm = reactive({
    "goodsId": "",
    "production_Batch": "",
    "quality_Guarantee": "",
    "production_License": "",
    "manufacturing_Enterprise": "",
    "information_Completeness": "",
    "cover_Image": "",
    "createName": " ",
    "createTime": " ",
    "updateName": ""
});

const addRules = {
    goodsId: [
        { required: true, message: '请选择商品名称', trigger: 'change' }
    ],
    production_Batch: [
        { required: true, message: '请输入生产批次', trigger: 'blur' },
        { pattern: /^.{1,30}$/, message: '最多支持30位字符', trigger: 'blur' }
    ],
    quality_Guarantee: [
        { required: true, message: '请输入保质期', trigger: 'blur' },
        { pattern: /^\d{1,5}$/, message: '只允许输入最多5位数字', trigger: 'blur' }
    ],
    production_License: [
        { required: true, message: '请输入生产许可证号', trigger: 'blur' },
        { pattern: /^[A-Za-z0-9]{1,30}$/, message: '只允许输入数字和字母，最多30位', trigger: 'blur' }
    ],
    manufacturing_Enterprise: [
        { required: true, message: '请输入生产企业', trigger: 'blur' },
        { pattern: /^[\u4e00-\u9fa5A-Za-z]{1,30}$/, message: '只允许输入中文或字母，最多30位，不允许特殊字符', trigger: 'blur' }
    ]
    // 移除封面图的必填验证，使其变为可选
};

function handleSelectionChange(val: any[]) {
    multipleSelection.value = val;
}

function onDetail(row: any) {
    // 跳转到FarmShowView页面，并传递当前行数据
    router.push({
        path: '/FarmShow',
        query: {
            traceabilityId: row.traceabilityId,
        }
    });
}

function onEdit(row: any) {
    isEdit.value = true;
    editId.value = row.traceabilityId;
    // 将当前行数据赋值到addForm
    addForm.goodsId = row.goodsId;
    addForm.production_Batch = row.production_Batch;
    addForm.quality_Guarantee = row.quality_Guarantee;
    addForm.production_License = row.production_License;
    addForm.manufacturing_Enterprise = row.manufacturing_Enterprise;
    addForm.information_Completeness = row.information_Completeness;
    addForm.cover_Image = row.cover_Image;
    addDialogVisible.value = true;
}

// 新增按钮处理
function onAdd() {
    isEdit.value = false;
    editId.value = null;
    resetForm();
    addDialogVisible.value = true;
}

// 重置表单
function resetForm() {
    addForm.goodsId = "";
    addForm.production_Batch = "";
    addForm.quality_Guarantee = "";
    addForm.production_License = "";
    addForm.manufacturing_Enterprise = "";
    addForm.information_Completeness = "";
    addForm.cover_Image = "";
    addForm.createName = " ";
    addForm.createTime = " ";
    addForm.updateName = "";

    // 重置表单验证状态
    if (addFormRef.value) {
        addFormRef.value.resetFields();
    }
}

// 弹窗关闭处理
function onDialogClose() {
    resetForm();
    isEdit.value = false;
    editId.value = null;
}

function onDelete(traceabilityId: any) {
    // 删除逻辑
    ElMessageBox.confirm(
        '你确定要删除吗?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            Write.post("/Management/TraceabilityDelete", {
                traceabilityId: traceabilityId
            }).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message);
                    GetTraceability();
                }
                else {
                    ElMessage.error(res.data.message);
                    return;
                }
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
function openExportDialog(row: any) {
    exportRow.value = row;
    exportDialogVisible.value = true;
}
function onExport() {
    if (!exportRow.value) {
        ElMessage.error('未选择导出数据');
        return;
    }
    // 改为GET请求，参数通过params传递
    Write.get('/Management/ExportTraceability', {
        params: {
            traceabilityId: exportRow.value.traceabilityId,
            numberOfExports: exportCount.value
        }
    }).then(res => {
        console.log('导出响应:', res);
        // 1. 如果后端返回的是下载链接
        if (typeof res.data === 'string' && res.data.startsWith('http')) {
            ElMessage.success('导出成功，正在下载...');
            window.open(res.data, '_blank');
            exportDialogVisible.value = false;
            return;
        }
        // 2. 如果后端返回的是CSV内容
        if (typeof res.data === 'string' && res.data.includes('TraceabilityId')) {
            // 可以弹窗显示或自动下载
            ElMessage.success('导出成功，已生成数据');
            // 你可以自动下载CSV
            const blob = new Blob([res.data], { type: 'text/csv' });
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'traceability.csv';
            a.click();
            window.URL.revokeObjectURL(url);
            exportDialogVisible.value = false;
            return;
        }
        // 3. 如果后端返回标准JSON
        if (res.data && res.data.code === 200) {
            ElMessage.success(res.data.message || '导出成功');
            exportDialogVisible.value = false;
        } else {
            console.log('导出失败返回:', res.data);
            ElMessage.error(res.data.message || '导出失败');
        }
    }).catch(err => {
        console.log('导出异常:', err, err?.response?.data);
        ElMessage.error('导出失败: ' + (err?.response?.data?.message || err?.message || '未知错误'));
    });
}
const handleCoverChange = async (option: any) => {
    // 使用旧的七牛云接口
    const formData = new FormData();
    formData.append('file', option.file);

    try {
        console.log('开始上传封面图...');
        const response = await axios.post('http://localhost:5228/api/Image/uploadToQiniu', formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
                'Authorization': 'Bearer ' + store.CurrentLogin.token
            }
        });

        console.log('封面图上传返回：', response.data);

        if (response.data && response.data.success === true) {
            addForm.cover_Image = response.data.data?.imageUrl || response.data.data?.url || response.data.url;
            console.log('设置封面图URL:', addForm.cover_Image);
            option.onSuccess && option.onSuccess(response.data, option.file);
            ElMessage.success('封面图上传成功');
        } else {
            throw new Error('上传失败：' + (response.data?.message || '服务器返回异常'));
        }
    } catch (error) {
        console.error('封面图上传失败:', error);
        ElMessage.error('封面图上传失败: ' + (error instanceof Error ? error.message : '未知错误'));
        option.onError && option.onError(error);
    }
};

// 删除封面图
const deleteCoverImage = () => {
    addForm.cover_Image = "";
    ElMessage.success('封面图已删除');
};
// 计算信息完整度百分比（只对商品名称、生产批次、生产许可证号必填，保质期和生产企业可空）
function calcCompleteness(formObj: any) {
    let count = 0;
    if (formObj.goodsId) count++;
    if (formObj.production_Batch) count++;
    if (formObj.production_License) count++;
    // 保质期和生产企业可空
    if (formObj.quality_Guarantee) count++;
    if (formObj.manufacturing_Enterprise) count++;
    // 总分还是5项，空的就不加分
    return Math.round((count / 5) * 100);
}
//新增
const onAddSave = () => {
    (addFormRef.value as any).validate((valid: boolean) => {
        if (!valid) {
            // 校验不通过，阻止提交
            return;
        }
        addForm.information_Completeness = String(calcCompleteness(addForm));
        // 只保留后端需要的字段
        const payload = {
            goodsId: addForm.goodsId,
            production_Batch: addForm.production_Batch,
            quality_Guarantee: addForm.quality_Guarantee,
            production_License: addForm.production_License,
            manufacturing_Enterprise: addForm.manufacturing_Enterprise,
            information_Completeness: addForm.information_Completeness,
            cover_Image: addForm.cover_Image,
            createName: store.CurrentLogin.userNickName,
            updateName: store.CurrentLogin.userNickName,
        };
        if (isEdit.value && editId.value) {
            // 修改
            Write.post('/Management/traceability/update', {
                traceabilityId: editId.value,
                ...payload
            }).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success('修改成功');
                    addDialogVisible.value = false;
                    isEdit.value = false;
                    editId.value = null;
                    resetForm(); // 重置表单
                    GetTraceability();
                } else {
                    ElMessage.error('修改失败');
                }
            }).catch(err => {
                console.log('后端返回:', err?.response?.data);
                ElMessage.error('修改失败: ' + (err?.response?.data?.message || ''));
            });
        } else {
            // 新增
            Write.post("/Management/traceability/create", payload).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success('保存成功');
                    addDialogVisible.value = false;
                    resetForm(); // 重置表单
                    GetTraceability();
                } else {
                    ElMessage.error('保存失败');
                }
            }).catch(err => {
                console.log('后端返回:', err?.response?.data);
                ElMessage.error('保存失败: ' + (err?.response?.data?.message || ''));
            });
        }
    });
}
// 批量删除
function onBatchDelete() {
    if (!multipleSelection.value.length) {
        ElMessage.warning('请先选择要删除的数据');
        return;
    }
    ElMessageBox.confirm(
        '你确定要批量删除选中的数据吗?',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            // 提取所有选中项的 traceabilityId
            const ids = multipleSelection.value.map(item => item.traceabilityId);
            Write.post('/Management/BatchLogicalDelete', { ids }).then(res => {
                if (res.data.code == 200) {
                    ElMessage.success(res.data.message || '批量删除成功');
                    GetTraceability();
                } else {
                    ElMessage.error(res.data.message || '批量删除失败');
                }
            }).catch(err => {
                console.log('后端返回:', err?.response?.data);
                ElMessage.error('批量删除失败: ' + (err?.response?.data?.message || ''));
            });
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消操作',
            })
        })
}
const data = ref<any>([])
const ShopShow = () => {
    Read.get("/Management/GoodShow").then(res => {
        data.value = res.data.data;
    })
}
watch(form, () => {
    GetTraceability();
})
onMounted(() => {
    ShopShow();
    GetTraceability();
})
</script>

<style scoped>
.show-bg {
    background: transparent;
    min-height: 100vh;
    padding: 0;
}

.toolbar {
    margin-bottom: 24px;
    display: flex;
    gap: 16px;
    padding: 0;
}

.toolbar .el-button {
    border-radius: 12px;
    font-weight: 500;
    transition: all 0.3s ease;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.toolbar .el-button:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.table-container {
    width: 100%;
    max-width: 100%;
    overflow-x: auto;
    background: transparent;
    box-sizing: border-box;
    padding: 0;
}

.avatar-uploader {
    width: 80px;
    height: 80px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    background: #fff;
}

.avatar-uploader-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 80px;
    height: 80px;
    border: 2px dashed #d9d9d9;
    border-radius: 6px;
    font-size: 32px;
    color: #8c939d;
    cursor: pointer;
}

.avatar {
    width: 100%;
    height: 80px;
    display: block;
    border-radius: 8px;
    object-fit: cover;
    border: 2px solid #409EFF;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

/* 表格样式优化 */
:deep(.el-table) {
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
    border: 1px solid rgba(255, 255, 255, 0.2);
}

:deep(.el-table th) {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    color: #2c3e50;
    font-weight: 600;
    border-bottom: 2px solid #e2e8f0;
    text-align: left;
    vertical-align: middle;
    padding: 16px 12px;
}

:deep(.el-table td) {
    border-bottom: 1px solid #f1f5f9;
    transition: all 0.3s ease;
    text-align: left;
    vertical-align: middle;
    padding: 16px 12px;
}

/* 特殊列对齐 */
:deep(.el-table .el-table__cell:first-child) {
    text-align: center;
}

:deep(.el-table .el-table__cell:nth-child(2)) {
    text-align: center;
}

:deep(.el-table .el-table__cell:nth-child(8)) {
    text-align: center;
}

:deep(.el-table .el-table__cell:last-child) {
    text-align: left;
}

:deep(.el-table tbody tr:hover td) {
    background: rgba(64, 158, 255, 0.05);
    transform: scale(1.01);
}

:deep(.el-table .el-table__row) {
    transition: all 0.3s ease;
}

:deep(.el-table .el-table__row:hover) {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 分页器样式 */
:deep(.el-pagination) {
    margin-top: 24px;
    justify-content: center;
}

:deep(.el-pagination .el-pager li) {
    border-radius: 8px;
    transition: all 0.3s ease;
}

:deep(.el-pagination .el-pager li.is-active) {
    background: linear-gradient(135deg, #409EFF 0%, #36a3f7 100%);
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 链接样式 */
:deep(.el-link) {
    font-weight: 500;
    transition: all 0.3s ease;
    margin-right: 12px;
    display: inline-block;
}

:deep(.el-link:last-child) {
    margin-right: 0;
}

:deep(.el-link:hover) {
    transform: translateY(-1px);
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 标签样式 */
:deep(.el-tag) {
    border-radius: 12px;
    font-weight: 500;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 弹窗样式 */
:deep(.el-dialog) {
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 12px 40px rgba(0, 0, 0, 0.15);
}

:deep(.el-dialog__header) {
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
    border-bottom: 1px solid #e2e8f0;
}

:deep(.el-dialog__title) {
    font-weight: 600;
    color: #2c3e50;
}

/* 表单样式 */
:deep(.el-form-item__label) {
    font-weight: 500;
    color: #2c3e50;
}

:deep(.el-input__wrapper) {
    border-radius: 8px;
    transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.2);
}

:deep(.el-input__wrapper.is-focus) {
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 选择器样式 */
:deep(.el-select .el-input__wrapper) {
    border-radius: 8px;
}

/* 上传组件样式 */
.avatar-uploader {
    border-radius: 12px;
    transition: all 0.3s ease;
    border: 2px dashed #d9d9d9;
}

.avatar-uploader:hover {
    border-color: #409EFF;
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.avatar-uploader-icon {
    border-radius: 12px;
    transition: all 0.3s ease;
}
</style>
